Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.IO
Imports System.Collections
Imports MyFramework
Imports System.Xml
Imports System.Text

Public Class ShippingForm
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
    Protected WithEvents ValidationSummary1 As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents txtStreetAddress As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtCity As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPhoneNumber As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtEmailAddr As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtConfirmEmailAddr As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlCountry As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtFullName As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtState As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPostalCode As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnSend As System.Web.UI.WebControls.Button
    Protected WithEvents Form1 As System.Web.UI.HtmlControls.HtmlForm
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator5 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents CustomValidator1 As System.Web.UI.WebControls.CustomValidator
    Protected WithEvents CustomValidator2 As System.Web.UI.WebControls.CustomValidator
    Protected WithEvents RequiredFieldValidator4 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents CustomValidator3 As System.Web.UI.WebControls.CustomValidator
    Protected WithEvents Requiredfieldvalidator6 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtCompanyName As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator7 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents cboTitle As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtFamilyName As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator8 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtGivenName As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator9 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents btnBack As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

#Region " Properties"
    Property AvailVolume() As String
        Get
            Return CType(viewstate("AvailVolume"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("AvailVolume") = Value
        End Set
    End Property

    Property SelVolume() As String
        Get
            Return CType(viewstate("SelVolume"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("SelVolume") = Value
        End Set
    End Property

    Property GoodWeight() As String
        Get
            Return CType(viewstate("GoodWeight"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("GoodWeight") = Value
        End Set
    End Property

    Property TotalPrice() As String
        Get
            Return CType(viewstate("TotalPrice"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("TotalPrice") = Value
        End Set
    End Property

    Property OrderNo() As String
        Get
            Return CType(viewstate("orderNo"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("orderNo") = Value
        End Set
    End Property

    Property UnitType() As String
        Get
            Return CType(viewstate("unitType"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("unitType") = Value
        End Set
    End Property

    Property MeasUnit() As String
        Get
            Return CType(viewstate("measUnit"), String)
        End Get
        Set(ByVal Value As String)
            viewstate("measUnit") = Value
        End Set
    End Property

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If (Not Page.IsPostBack) Then
            AvailVolume = Request.QueryString("totalVolAvail").ToString()
            SelVolume = Request.QueryString("totalVolSel").ToString()
            GoodWeight = Request.QueryString("totalGoodWeight").ToString()
            TotalPrice = Request.QueryString("totalPrice").ToString()
            OrderNo = Request.QueryString("orderNo").ToString()
            UnitType = Request.QueryString("unitType").ToString()
            MeasUnit = Request.QueryString("measUnit").ToString()

            If (ShoppingConext.ShopingUserId > 0) Then
                txtEmailAddr.Text = ShoppingConext.ShopingUserEmail
                txtConfirmEmailAddr.Text = ShoppingConext.ShopingUserEmail
            End If
        End If
        btnCancel.Attributes.Add("onclick", "javascript:return ShowConfirm();")

        txtEmailAddr.Attributes.Add("onfocus", "javascript:EmailAddrLostForcus1();")
        txtConfirmEmailAddr.Attributes.Add("onblur", "javascript:EmailAddrLostForcus2();")

    End Sub

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
        Try

            Dim sendShoppingListObj As SendShoppingList = New SendShoppingList
            With sendShoppingListObj
                .CompanyName = txtCompanyName.Text.Trim
                .CustomerName = cboTitle.SelectedValue & Convert.ToString(IIf(txtGivenName.Text.Trim = "", "", String.Format(" {0}", txtGivenName.Text.Trim))) & Convert.ToString(IIf(txtFamilyName.Text.Trim = "", "", " " & txtFamilyName.Text.Trim))
                .CustomerEmail = txtEmailAddr.Text.Trim
                .Address = String.Format("{0} <br> {1}, {2} <br> {3}", txtStreetAddress.Text, txtCity.Text.Trim, txtPostalCode.Text.Trim, ddlCountry.SelectedItem.Text)
                .PhoneNumber = txtPhoneNumber.Text.Trim
                .OrderDate = DateTime.Now.ToShortDateString()
                Try
                    .ConsolidationPoint = ConPointService.GetConPoint(ShoppingConext.ShopingSelectedConsolidation).Description
                Catch ex As Exception
                End Try
                If (OrderNo.Length > 0) Then
                    .OrderNumber = String.Format("Order No: {0}", OrderNo)
                Else
                    .OrderNumber = ""
                End If
                If (AvailVolume.Length > 0) Then
                    .TotalVolAvail = String.Format("Total Volume Available: {0} {1}", AvailVolume, UnitType)
                End If

                If (SelVolume.Length > 0) Then
                    .TotalVolSel = String.Format("Total Volume Selected: {0} {1}", SelVolume, UnitType)
                End If

                If (GoodWeight.Length > 0) Then
                    .GoodWeight = String.Format("Total Goods Selected: {0} {1}", GoodWeight, MeasUnit)
                End If

                .TotalPrice = String.Format("Total Price: {0}", TotalPrice)

                'Shopping List
                Dim oCollection As New Collection
                If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
                    oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
                Else
                    oCollection = DirectCast(Session("SS_SHOPPING_LIST_temp"), Collection)
                End If
                Dim sb As StringBuilder = New StringBuilder
                sb.Append("<table id='tblList' width='100%'><tr height='30px'>	<th class='CellWidth1'>	Item</th><th class='CellWidth2'>Product Code</th><th class='CellWidth3'>Description</th><th class='CellWidth4'>Order Qty</th><th class='CellWidth5'>Units</th><th class='CellWidth6' align='right'>Unit Price</th><th class='CellWidth7' align='right'>Total Price</th><th class='CellWidth9'>Notes</th></tr>")
                Dim item As New ShoppingItem
                For i As Integer = 1 To oCollection.Count
                    item = DirectCast(oCollection(i), ShoppingItem)
                    'Just shipping items that have Priority "Add"
                    'If (item.Priority = 1) Then
                    '    sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td align='right'>${5}</td><td align='right'>${6}</td><td>{7}</td></tr>", item.ItemNo, item.ProductCode, item.Description, item.Quantity, item.UnitDesc, item.UnitPrice, item.Total, item.Notes)
                    'End If

                    sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td align='center'>{3}</td><td>{4}</td><td align='right'>${5}</td><td align='right'>${6}</td><td>{7}</td></tr>", item.ItemNo, item.ProductCode, item.Description, item.Quantity, item.UnitDesc, item.UnitPrice.ToString(Config.DecimalFormatEx2), item.Total.ToString(Config.DecimalFormatEx2), item.Notes)
                Next
                sb.Append("	</table>")

                .ShoppingList = sb.ToString
            End With

            sendShoppingListObj.Send()

            'Save order list for admin's management (view/delete)
            Dim customerId As Integer = SaveCustomer()
            SaveShoppingList(customerId)

            If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
                Session("SS_SHOPPING_LIST_temp") = Session(Constant.SS_SHOPPING_LIST) ' prepare if user click back from browser
            End If
            ClearShoppingCartData()
            Response.Redirect("Complete.aspx")
        Catch ex As Exception
            Logger.Error("Failed to send SendShoppingListEmail", ex)
        End Try

    End Sub

    Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
        Try
            Response.Redirect("ShoppingCartList.aspx")
        Catch ex As Exception
        End Try
    End Sub

    Private Sub GotoIMStockPage()
        Dim strURL As String = "IMStockReport.aspx?teid={2}&ownerid=-2&showfob=1&cpid={0}&qty={1}&sort={3}&countryid={4}"
        Dim result As String = "IMStockReport.aspx?teid=-1&ownerid=-2&showfob=1&cpid=0"
        Dim params As New Common.IMStockReportParams

        If Not Session("IMStockReportParams") Is Nothing Then
            params = DirectCast(Session("IMStockReportParams"), Common.IMStockReportParams)
            result = String.Format(strURL, params.ConPointID, params.Quantity, params.TerritoryId, params.IDSSort, params.CountryId)
        End If
        Response.Redirect(result)
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        ClearShoppingCartData()
        GotoIMStockPage()
    End Sub

    Private Sub ClearShoppingCartData()
        Session(Constant.SS_SHOPPING_LIST) = Nothing ' clear shopping list
        Session(Constant.txtExistingOrderVolume) = Nothing ' clear shopping list
        Session(Constant.txtHalfPallet) = Nothing ' clear shopping list
        Session(Constant.txtOrderNo) = Nothing ' clear shopping list
        Session(Constant.txtQty20Cont) = Nothing ' clear shopping list
        Session(Constant.txtQty40Cont) = Nothing ' clear shopping list
        Session(Constant.txtQty40HiCube) = Nothing ' clear shopping list
        Session(Constant.rdPartOrder) = Nothing ' clear shopping list
        Session(Constant.ddlCountry) = Nothing ' clear shopping list
        RequestContext.CurrentDestinationCountry = Nothing
        Session(Constant.SS_CONPOINT_ID) = Nothing
        Session(ShoppingConext.ShopingSelectedConsolidation.ToString()) = Nothing
        Session(Constant.SS_SELECTED_CONPOINT_ID) = Nothing
    End Sub

    Private Sub SaveShoppingList(ByVal customerId As Integer)
        Dim shoppingCartList As New ShoppingListCollection
        'Shopping List
        Dim oCollection As New Collection
        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If
        Dim shopItem As ShoppingItem
        Dim shoppingItemDB As New ShoppingList
        If (Not oCollection Is Nothing AndAlso oCollection.Count > 0) Then
            For i As Integer = 1 To oCollection.Count
                shopItem = DirectCast(oCollection(i), ShoppingItem)
                shoppingItemDB = New ShoppingList
                shoppingItemDB.IDSSort = shopItem.ItemNo
                shoppingItemDB.ProductCode = shopItem.ProductCode
                shoppingItemDB.Description = shopItem.Description
                shoppingItemDB.Qty = shopItem.Quantity
                shoppingItemDB.UnitSetting = shopItem.UnitDesc
                shoppingItemDB.UnitPrice = Convert.ToDecimal(shopItem.UnitPrice)
                shoppingItemDB.TotalPrice = Convert.ToDecimal(shopItem.Total)
                shoppingItemDB.PriorityIndex = shopItem.Priority
                shoppingItemDB.Notes = shopItem.Notes
                shoppingItemDB.BulkOrderId = shopItem.BulkOrderId
                shoppingItemDB.UnitSettingID = shopItem.UnitSettingID
                shoppingItemDB.UnitWeight = shopItem.UnitWeight
                shoppingItemDB.MinQtyVolume = shopItem.MinQtyVolume
                shoppingItemDB.TerritoryID = shopItem.TerritoryID
                shoppingCartList.Add(shoppingItemDB)
            Next
        End If

        Dim shoppingOrder As New shoppingOrder
        shoppingOrder.UserId = ShoppingConext.ShopingUserId
        shoppingOrder.OrderType = Convert.ToBoolean(IIf(Session(Constant.rdPartOrder) Is Nothing, True, Not CType(Session(Constant.rdPartOrder), Boolean))) '1: for a full container of goods all selected from the IDS ; 0 : Forms part of a existing production order 
        shoppingOrder.DestinationCountryId = Convert.ToInt32(IIf(Session(Constant.ddlCountry) Is Nothing, 0, CType(Session(Constant.ddlCountry), Integer)))
        If (shoppingOrder.OrderType) Then
            Try
                shoppingOrder.Qty20 = Convert.ToInt32(IIf(Not Session(Constant.txtQty20Cont) Is Nothing, IIf(CType(Session(Constant.txtQty20Cont), String) > "", Session(Constant.txtQty20Cont), 0), 0))
            Catch ex As Exception
            End Try
            Try
                shoppingOrder.Qty40 = Convert.ToInt32(IIf(Not Session(Constant.txtQty40Cont) Is Nothing, IIf(CType(Session(Constant.txtQty40Cont), String) > "", Session(Constant.txtQty40Cont), 0), 0))
            Catch ex As Exception
            End Try
            Try
                shoppingOrder.Qty40HC = Convert.ToInt32(IIf(Not Session(Constant.txtQty40HiCube) Is Nothing, IIf(CType(Session(Constant.txtQty40HiCube), String) > "", Session(Constant.txtQty40HiCube), 0), 0))
            Catch ex As Exception
            End Try
        Else
            shoppingOrder.OrderNo = Convert.ToString(IIf(Session(Constant.txtOrderNo) Is Nothing, "", Session(Constant.txtOrderNo)))
            Try
                shoppingOrder.HalfPalletSpaces = Convert.ToDecimal(IIf(Not Session(Constant.txtHalfPallet) Is Nothing, IIf(CType(Session(Constant.txtHalfPallet), String) > "", Session(Constant.txtHalfPallet), 0), 0))
            Catch ex As Exception
            End Try
            Try
                shoppingOrder.FilledVolume = Convert.ToDecimal(IIf(Not Session(Constant.txtExistingOrderVolume) Is Nothing, IIf(CType(Session(Constant.txtExistingOrderVolume), String) > "", Session(Constant.txtExistingOrderVolume), 0), 0))
            Catch ex As Exception
            End Try
        End If
        shoppingOrder.ConPointID = ShoppingConext.ShopingSelectedConsolidation
        ShoppingListService.CreateShoppingCartList(shoppingCartList, shoppingOrder, ShoppingConext.ShopingUserId, customerId)
    End Sub

    Private Function SaveCustomer() As Integer
        Dim customer As New ShoppingCustomer
        With customer
            .City = txtCity.Text.Trim()
            .CompanyName = txtCompanyName.Text.Trim()
            .Country = ddlCountry.SelectedItem.Text
            .EmailAddress = txtEmailAddr.Text.Trim()
            .FamilyName = txtFamilyName.Text.Trim()
            .GivenName = txtGivenName.Text.Trim()
            .State = txtState.Text.Trim()
            .StreetAddress = txtStreetAddress.Text.Trim()
            .Title = cboTitle.SelectedItem.Text
            .ZipCode = txtPostalCode.Text.Trim()
            .PhoneNumber = txtPhoneNumber.Text.Trim()
        End With
        Return ShoppingListService.CreateShoppingCustomer(customer)
    End Function
End Class
